package me.pppploi8.webmcs.main;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.handler.ResourceHandler;
import org.eclipse.jetty.server.session.SessionHandler;

import me.pppploi8.webmcs.http.jetty.CommonHandler;
import me.pppploi8.webmcs.main.filter.WebmcsCSRFFilter;
import me.pppploi8.webmcs.main.filter.WebmcsCoreFilter;
import me.pppploi8.webmcs.main.filter.WebmcsSaveLoginStatusFilter;
import me.pppploi8.webmcs.main.urlmapping.WebmcsCoreService;
import me.pppploi8.webmcs.main.urlmapping.WebmcsFileService;
import me.pppploi8.webmcs.main.urlmapping.WebmcsLoginSerivce;
import me.pppploi8.webmcs.main.urlmapping.WebmcsSecurityService;
import me.pppploi8.webmcs.main.urlmapping.WebmcsSettingService;
import me.pppploi8.webmcs.main.urlmapping.WebmcsTaskService;
import me.pppploi8.webmcs.minecraft.server.core.McServerCore;
import me.pppploi8.webmcs.minecraft.server.core.McServerFactory;
import me.pppploi8.webmcs.minecraft.server.struct.McMessageInterface;
import me.pppploi8.webmcs.task.TaskManage;
import me.pppploi8.webmcs.task.TaskManageFactory;
/**
 * WebMCS入口函数
 * @author pppploi8
 */
public class Main {
    private final static boolean DEBUG = false;

    public static void main(String[] args) throws IOException {
        System.out.println("[WebMCS]正在启动HTTP服务，请稍后...");
        String curPath;
        if (DEBUG){
            curPath = "./build_run/";
        }else{
            curPath = new File("").getCanonicalFile().getPath(); 
        }
        Map<String,String> configMap = getStartConfig(args);
        //初始化启动参数
        int port = getIntByString(configMap.get("-port"), 23333);
        McServerCore mcs = McServerFactory.createMcServer(curPath);
        TaskManage tm = TaskManageFactory.createTaskManage(mcs);
        mcs.setMessageNotice(new McMessageInterface() {
			@Override
			public void message(String message) {
				System.out.print("[SERVER]" + message);
			}
		});
        //配置Web服务器
        CommonHandler handler = new CommonHandler();
		handler
			.addFilter("(.*\\.mcs|.*\\.login)", WebmcsCSRFFilter.class)
			.addFilter("(.*\\.mcs|.*\\.login)", WebmcsSaveLoginStatusFilter.class)
			.addFilter(".*\\.mcs", WebmcsCoreFilter.class)
			.addUrlMapping("/login/", ".login", WebmcsLoginSerivce.class)
			.addUrlMapping("/core/server/", ".mcs", WebmcsCoreService.class)
			.addUrlMapping("/setting/", ".mcs", WebmcsSettingService.class)
			.addUrlMapping("/core/task/", ".mcs", WebmcsTaskService.class)
			.addUrlMapping("/core/file/", ".mcs", WebmcsFileService.class)
			.addUrlMapping("/security/", ".security", WebmcsSecurityService.class);
		Server server = new Server(port);
		ResourceHandler resourceHandler = new ResourceHandler();  
		server.insertHandler(handler);
		server.insertHandler(new SessionHandler());
        server.insertHandler(resourceHandler);
        if (DEBUG) {
            resourceHandler.setResourceBase("../web");
        } else {
            resourceHandler.setResourceBase("./web/");
        }
        try {
        	server.start();
            System.out.println("[WebMCS]HTTP服务已成功运行，请打开网页：http://127.0.0.1:" + port + "/ 来控制Minecraft服务端");
            System.out.println("[WebMCS]如果要关闭WebMCS请输入webmcs stop指令，查看其他指令请输入webmcs help");
            Scanner sc = new Scanner(System.in);
            String text;
            while ((text = sc.nextLine()) != null){
                if(text.equalsIgnoreCase("webmcs stop")){
                    if (mcs.getServerStatus()) {
                        mcs.stop();
                        System.out.println("[WebMCS]请等待minecraft服务器退出后再次执行命令来退出WebMCS！");
                        continue;
                    }
                    tm.stopTask();
                    break;
                }else if(text.equalsIgnoreCase("webmcs help")){
                	System.out.println("[WebMCS]后台支持指令如下:");
                	System.out.println("  webmcs start       #启动minecraft服务器");
                	System.out.println("  webmcs stop        #强制退出minecraft服务器并关闭WebMCS");
                	System.out.println("  webmcs termination #强制关闭minecraft服务器（这将导致服务器回档，慎用）");
                	System.out.println("  其他指令将直接转发给minecraft服务器后台");
                	System.out.println("[WebMCS]-----------");
                }else if(text.equalsIgnoreCase("webmcs start")){
                	if (mcs.getServerStatus())
                		System.out.println("[WebMCS]服务器正在运行，请不要重复开服");
                	else
                		mcs.start();
                }else if(text.equalsIgnoreCase("webmcs termination")){
                	if (mcs.getServerStatus()){
                		mcs.termination();
                		System.out.println("[WebMCS]服务器已强制关闭！");
                	}else
                		System.out.println("[WebMCS]服务器不在运行，无需强制关闭");
                }else{
                	if (mcs.getServerStatus())
                		mcs.sendMessage(text);
                	else
                		System.out.println("[WebMCS]服务器不在运行，请先通过网页或者webmcs start命令启动服务器");
                }
            }
            server.stop();
            sc.close();
        } catch (Exception e) {
            System.out.println("HTTP服务启动失败，请更换端口重试。");
            tm.stopTask();
        }
    }
	private static Map<String,String> getStartConfig(String[] args){
        Map<String,String> configMap = new TreeMap<>();
        for (int i=0;i<args.length;){
            try{
                configMap.put(args[i++], args[i++]);
            }catch(Exception e){ }
        }
        return configMap;
    }
    private static int getIntByString(String num,int defnum){
        try {
            int rnum = Integer.parseInt(num);
            return rnum;
        } catch (Exception e) {
            return defnum;
        }
    }
}
